<template>
  <div id="testSetting">
    <div class="tree-table">
      <el-tree :expand-on-click-node="false" ref="dataTree" :default-expand-all="true" :data="clsList" :props="defaultProps" node-key="id" highlight-current
        @node-click="handleClickClass" class="tools-tree">
        <template #default="{ data }">
          <div class="custom-tree-node">
            <span>{{ data.order }}. {{ data.name }}</span>
            <span>
              <el-button v-if="data.id === null" type="success" class="addCirBtn" size="small" icon="Plus" circle @click="appendClass()"></el-button>
              <template v-else>
                <el-button type="warning" class="cirBtn" size="small" icon="EditPen" circle @click="editClass(data)"></el-button>
                <el-button type="info" class="cirBtn" size="small" icon="Delete" circle @click="deleteClass(data.id)"></el-button>
              </template>
            </span>
          </div>
        </template>
      </el-tree>
      <div class="tools">
        <el-divider content-position="left">{{ sltClassNode.name }}</el-divider>
        <el-button class="addAdvBtn" type="primary" @click="handleAddItem">新建项目</el-button>
        <el-table v-loading="loading" row-key="id" :data="itemList">
          <el-table-column label="序号" width="70" align="center">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handleEditItem(scope.row)">
                {{
                scope.row.name
                }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="编号" width="100" align="center"></el-table-column>
          <el-table-column label="类型" width="100" align="center">
            <template #default="scope">{{ formatType(scope.row.type) }}</template>
          </el-table-column>
          <el-table-column prop="order" label="排序号" width="100" align="center"></el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button size="small" icon="EditPen" type="primary" plain circle @click="handleEditItem(scope.row)"></el-button>
              <el-button size="small" type="danger" icon="Delete" plain circle @click="handleDeleteItem(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog title="检验分类设置" :show-close="false" v-model="showDialog" :close-on-click-modal="false" width="500px">
        <el-form ref="clsFormRef" :model="clsForm" :rules="clsRule" label-width="60px" class="form-input-m" :inline-message="true">
          <el-form-item prop="name" label="名称">
            <el-input type="text" v-model="clsForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编号">
            <el-input type="text" v-model="clsForm.code" placeholder="请输入编号"></el-input>
          </el-form-item>
          <el-form-item prop="short" label="简称">
            <el-input type="text" v-model="clsForm.short" placeholder="请输入简称"></el-input>
          </el-form-item>
          <!-- <el-form-item prop="type" label="类型">
            <el-radio-group v-model="clsForm.type">
              <el-radio :label="0">数值</el-radio>
              <el-radio :label="2">文本</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item prop="order" label="排序号">
            <el-input-number v-model="clsForm.order" :min="1" :max="1000" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="saveClass(clsFormRef)">保存</el-button>
          <el-button @click="closeClsDialog(clsFormRef)">取消</el-button>
        </template>
      </el-dialog>
      <el-dialog title="项目设置" :show-close="false" v-model="showPmsDialog" :close-on-click-modal="false" width="700px">
        <!-- 权限点表单 -->
        <el-form ref="itemFormRef" :model="itemForm" :rules="itemRule" label-width="100px" class="form-input-m" :inline-message="true">
          <el-form-item prop="name" label="名称">
            <el-input type="text" v-model="itemForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item prop="code" label="编号">
            <el-input type="text" v-model="itemForm.code" placeholder="请输入编号"></el-input>
          </el-form-item>
          <el-form-item prop="type" label="类型">
            <el-radio-group v-model="itemForm.type" @change="(changed:any) => handleChange(changed)">
              <el-radio :label="0">文本框</el-radio>
              <el-radio :label="2">下拉框</el-radio>
              <el-radio :label="4">范围值</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="options" v-show="itemForm.type === 2" label="选项值" class="input-s defTable">
            <el-table row-key="$index" :data="itemForm.options" style="width: 100%" size="small">
              <el-table-column label="选项名称" width="150" align="center">
                <template #default="scope">
                  <el-input type="text" size="small" class="w150" v-model="scope.row.name" maxlength="20"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="选项编号" width="150" align="center">
                <template #default="scope">
                  <el-input type="text" size="small" class="w150" v-model="scope.row.code" maxlength="20"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="150" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.status" placeholder="请选择状态">
                    <el-option :label="'正常'" :value="'M'"></el-option>
                    <el-option :label="'偏高'" :value="'H'"></el-option>
                    <el-option :label="'偏低'" :value="'L'"></el-option>
                    <el-option :label="'阳性'" :value="'P'"></el-option>
                    <el-option :label="'弱阳'" :value="'W'"></el-option>
                    <el-option :label="'错误'" :value="'E'"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="排序号" width="150" align="center">
                <template #default="scope">
                  <el-input-number size="small" v-model="scope.row.order" :min="1" :max="1000" />
                </template>
              </el-table-column>
              <el-table-column width="70" property="address" label="操作" align="center">
                <template #default="scope">
                  <el-button size="small" type="danger" icon="Delete" plain circle @click="removeOption(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item prop="options" v-show="itemForm.type === 2">
            <el-button icon="CirclePlus" size="small" @click="addOption()">添加行</el-button>
          </el-form-item>
          <el-form-item prop="minValue" v-show="itemForm.type===4" label="参考最小值">
            <el-input type="text" v-model="itemForm.minValue" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="maxValue" v-show="itemForm.type===4" label="参考最大值">
            <el-input type="text" v-model="itemForm.maxValue" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item prop="unit" label="单位">
            <el-input type="text" v-model="itemForm.unit" placeholder="请输入单位"></el-input>
          </el-form-item>
          <el-form-item prop="order" label="排序号">
            <el-input-number v-model="itemForm.order" :min="1" :max="1000" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="saveItemForm(itemFormRef)">保存</el-button>
          <el-button @click="closeItemDialog(itemFormRef)">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
import type { ElTree, FormInstance } from 'element-plus';
import { AppStore } from '../../stores/store';
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let dataTree: any = ref<InstanceType<typeof ElTree>>();
let loading = ref(false);
const itemFormRef = ref<FormInstance>();
const clsFormRef = ref<FormInstance>();
let clsList: any = reactive([
  {
    id: null,
    name: '检验分类',
    children: []
  }
]);
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 当前选中的节点
let sltClassNode = reactive({
  id: '',
  name: ''
});
let showDialog = ref(false);
let clsForm = reactive({
  id: '',
  orgId: store.userInfo.orgId,
  name: '',
  code: '',
  short: '', //简称
  // type: null, //类型
  order: 0
});
let clsRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
};
let itemList: any = reactive([]);
let showPmsDialog = ref(false);
let itemForm: any = reactive({
  id: '',
  classId: '',
  name: '',
  code: '',
  type: null,
  options: [],
  minValue: null,
  maxValue: null,
  unit: '',
  order: 0
});
// 表单验证
let itemRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: '请输入编号',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择类型',
      trigger: 'change'
    }
  ]
};

findClassList();

function findClassList() {
  const url = '/api/test/findTestClassList';
  proxy.$http
    .get(url, { params: { orgId: store.userInfo.orgId } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        clsList[0].children.length = 0;
        clsList[0].children.push(...res.data.list);
        if (clsList[0].children.length > 0) {
          sltClassNode.id = clsList[0].children[0].id;
          sltClassNode.name = clsList[0].children[0].name;
          setCurClassNode(clsList[0].children[0].id);
          findClassItemList();
        }
      }
    })
    .catch((err: string) => {
      notifyMessage(err, notifyType.warning, proxy);
    });
}
// 光标定位在指定分类上
function setCurClassNode(nodeId: string) {
  nextTick(() => {
    dataTree.value.setCurrentKey(nodeId);
  });
}
function findClassItemList() {
  loading.value = true;
  itemList.length = 0;
  const url = '/api/test/findTestClassItemListByClassId';
  // 将标题的id给列表获取数据用到的的typeId
  proxy.$http
    .get(url, { params: { classId: sltClassNode.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        itemList.push(...res.data.itemList);
      }
      loading.value = false;
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}
function formatType(value: number) {
  switch (value) {
    case 0:
      return '文本框';
    case 2:
      return '下拉框';
    case 4:
      return '范围值';
    default:
      return '';
  }
}

function handleChange(label: number) {
  if (label === 0) {
    itemForm.range = null;
  }
}
// 点击分类项
function handleClickClass(obj: any) {
  if (obj.id === null) {
    return;
  }
  sltClassNode.id = obj.id;
  sltClassNode.name = obj.name;
  findClassItemList();
}
//添加分类
function appendClass() {
  showDialog.value = true;
  clsForm.order = clsList[0].children.length + 1;
}
// 编辑分类
function editClass(row: any) {
  clsForm.id = row.id;
  clsForm.name = row.name;
  clsForm.code = row.code;
  clsForm.short = row.short;
  clsForm.order = row.order;
  showDialog.value = true;
}
//保存
function saveClass(clsFormRef: any) {
  if (!clsFormRef) return;
  clsFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    //判断添加和编辑
    let url = '';
    if (clsForm.id) {
      url = '/api/test/editTestClass';
    } else {
      url = '/api/test/addTestClass';
    }
    proxy.$http
      .post(url, clsForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showDialog.value = false;
          if (clsForm.id) {
            // 编辑保存
            const curNode = dataTree.value.getCurrentNode();
            curNode.name = clsForm.name;
            curNode.code = clsForm.code;
            curNode.short = clsForm.short;
            sltClassNode.id = clsForm.id;
            sltClassNode.name = clsForm.name;
          } else {
            // 添加保存
            const temp = {
              id: res.data.testClassId,
              name: clsForm.name,
              code: clsForm.code,
              short: clsForm.short
            };
            clsList[0].children.push(temp);
            setCurClassNode(temp.id);
            sltClassNode.id = temp.id;
            sltClassNode.name = temp.name;
            findClassItemList();
          }
          clearClassForm();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}

function clearClassForm() {
  clsForm.id = '';
  clsForm.name = '';
  clsForm.code = '';
  clsForm.short = '';
  clsForm.order = 0;
}
// 取消添加
function closeClsDialog(clsFormRef: any) {
  if (!clsFormRef) return;
  clsFormRef.clearValidate();
  clearClassForm();
  showDialog.value = false;
}
// 删除
function deleteClass(id: string) {
  proxy
    .$confirm('确定删除此分类?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/test/deleteTestClass';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findClassList();
            if (clsList[0].children.length > 0) {
              setCurClassNode(clsList[0].children[0].id);
            }
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
function handleAddItem() {
  if (!sltClassNode.id) {
    notifyMessage('请先添加分类', notifyType.warning, proxy);
    return;
  }
  showPmsDialog.value = true;
  itemForm.classId = sltClassNode.id;
  itemForm.order = itemList.length + 1;
}
function handleEditItem(row: any) {
  itemForm.id = row.id;
  itemForm.classId = row.classId;
  itemForm.name = row.name;
  itemForm.code = row.code;
  itemForm.type = row.type;
  itemForm.options = row.options ? JSON.parse(row.options) : [];
  itemForm.minValue = row.minValue;
  itemForm.maxValue = row.maxValue;
  itemForm.unit = row.unit;
  itemForm.order = row.order;
  showPmsDialog.value = true;
}
function addOption() {
  itemForm.options.push({ name: '', code: '', order: itemForm.options.length + 1 });
}
function removeOption(idx: number) {
  itemForm.options.splice(idx, 1);
}
function saveItemForm(itemFormRef: any) {
  if (!itemFormRef) return;
  itemFormRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const postData = {
      id: itemForm.id,
      classId: itemForm.classId,
      name: itemForm.name,
      code: itemForm.code,
      type: itemForm.type,
      options: JSON.stringify(itemForm.options),
      minValue: itemForm.minValue,
      maxValue: itemForm.maxValue,
      unit: itemForm.unit,
      order: itemForm.order
    };

    //判断添加和编辑
    let url = '';
    if (itemForm.id) {
      url = '/api/test/editTestClassItem';
    } else {
      url = '/api/test/addTestClassItem';
    }
    proxy.$http
      .post(url, postData)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showPmsDialog.value = false;
          clearItemForm();
          findClassItemList();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}
function clearItemForm() {
  itemForm.id = '';
  itemForm.name = '';
  itemForm.code = '';
  itemForm.type = null;
  itemForm.options = [];
  itemForm.unit = '';
  itemForm.classId = '';
  itemForm.order = 0;
}
function closeItemDialog(itemFormRef: any) {
  if (!itemFormRef) return;
  itemFormRef.clearValidate();
  clearItemForm();
  showPmsDialog.value = false;
}
function handleDeleteItem(id: string) {
  proxy
    .$confirm('确定删除此项目?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/test/deleteTestClassItem';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findClassItemList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
</script>
<style lang="scss" scoped>
#testSetting {
  //左树右表结构
  .tree-table {
    // margin-top: 10px;
    display: flex;
    min-height: 400px;
    .tools-tree {
      width: 15%;
      min-width: 150px;
      margin: 0 0 0 0;
      padding: 5px;
      font-size: $font-size;
      border: none;
      .addCirBtn {
        width: 18px;
        height: 18px;
        padding: 0px;
        margin-left: 10px;
      }
      .cirBtn {
        display: none;
        width: 16px;
        height: 16px;
        padding: 0px;
        margin-left: 10px;
      }
      .el-tree-node__content:hover {
        .cirBtn {
          display: inline-block !important;
        }
      }
    }
    .tools {
      width: 85%;
      margin: 0 0 0 1px;
      .el-divider {
        width: 100%;
      }
      .el-divider--horizontal {
        margin: 7px 0 20px 0;
      }
      .addAdvBtn {
        margin-bottom: 10px;
      }
      .el-divider__text {
        font-size: $font-size;
      }
      .el-dialog__body {
        padding-top: 20px;
      }
      .divider {
        width: 310px;
        .el-divider__text {
          font-weight: bold;
          font-size: $font-size;
        }
      }
    }
  }
  .defTable .el-table th {
    padding: 5px 0px !important;
  }
}
</style>
